package com.ycwl.aiLive_2d.thread;

import com.ycwl.aiLive_2d.utils.AudioUtils;
import com.ycwl.aiLive_2d.utils.FileSplitUtils;
import lombok.extern.slf4j.Slf4j;

import java.util.*;
import java.util.concurrent.*;

import static com.ycwl.aiLive_2d.thread.MouthThreadReturnByThreadPool.queueMap;

/**
 * @author songmingsong
 * @date 2023/7/10
 */
@Slf4j
public class MouthThreadPoolExecutor {
    // 核心线程数
    private static final int CORE_POOL_SIZE = 5;
    // 最大线程数
    private static final int MAX_POOL_SIZE = 10;
    // 任务队列
    private static final int QUEUE_CAPACITY = 100;
    // 等待时间
    private static final Long KEEP_ALIVE_TIME = 1L;

    private static final List<String> saveFileNameList = Arrays.asList(
            "/streaming_tts_0.wav",
            "/streaming_tts_1.wav",
            "/streaming_tts_2.wav",
            "/streaming_tts_3.wav",
            "/streaming_tts_4.wav"
    );

    public static void startPase(String splitFilePath, String copyFilePath, String uid) {

        ThreadPoolExecutor executor = new ThreadPoolExecutor(
                CORE_POOL_SIZE,
                MAX_POOL_SIZE,
                KEEP_ALIVE_TIME,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(QUEUE_CAPACITY),
                new ThreadPoolExecutor.CallerRunsPolicy());

        log.info("-> 清空 queueMap -> {}", uid);
        if (Objects.nonNull(queueMap.get(uid))) {
            queueMap.get(uid).clear();
        }
        Double voiceLength = AudioUtils.getVoiceLength(copyFilePath);
        int lengthWav = 5; // wav播放时长不超过这个值
        if (voiceLength <= lengthWav) {
            // 时长小于5秒 不切片
            log.info("-> 时长小于" + lengthWav + "秒 不切片->{}", copyFilePath);
            int i = 0;
            Runnable worker = new MouthThreadReturnByThreadPool(uid, copyFilePath, i);
            executor.execute(worker);
        } else {
            log.info("-> 开始对文件切片->{}", copyFilePath);
            FileSplitUtils.getSplitFile(copyFilePath, 5, splitFilePath);
            log.info("-> 切片完成,开始解析数据片段->{}", uid);
            for (int i = 0; i < saveFileNameList.size(); i++) {
                MouthThreadReturnByThreadPool worker = new MouthThreadReturnByThreadPool(uid, splitFilePath + saveFileNameList.get(i), i);
                executor.execute(worker);
            }
            //终止线程池
            executor.shutdown();
            log.info("-> 关闭线程池->{}", uid);
        }
    }
}
